package com.atomic.test.example.service.impl;

import com.atomic.test.example.entity.User;
import com.atomic.test.example.exception.CRUDException;
import com.atomic.test.example.exception.ExceptionCode;
import com.atomic.test.example.query.BaseQuery;
import com.atomic.test.example.query.PageList;
import com.atomic.test.example.repository.UserRepository;
import com.atomic.test.example.service.IUserService;
import com.atomic.test.example.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Observable;

/**
 * Created by DreamYao on 2017/1/24.
 */
@Service
public class UserServiceImpl extends Observable implements IUserService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 用户注册
     *
     * @param user
     */
    @Override
    public void save(User user) {
        User queryUser = null;
        try {
            queryUser = userRepository.getUserByUserName(user.getUserName());
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        if (queryUser != null) {
            throw new CRUDException(ExceptionCode.DATA_CONVERT_ERROR, "此用户名已被注册!");
        }
        user.setLastVisit(new Date());
        user.setLastIp(UserContext.getRequest().getRemoteAddr());
        userRepository.save(user);
    }

    /**
     * 用户删除
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        User user = this.get(id);
        if (user != null) {
            userRepository.delete(user);
        } else {
            throw new CRUDException(ExceptionCode.HAVE_NOT_DATA, "删除的用户不存在");
        }
    }

    /**
     * 根据用户ID获取用户信息
     *
     * @param id t_user表主键Id
     * @return
     */
    @Override
    public User get(Integer id) throws NullPointerException {
        return userRepository.getUserById(id);
    }

    @Override
    public PageList findPage(BaseQuery baseQuery) {
        return null;
    }

    @Override
    public List<User> getAll() {
        return null;
    }

    /**
     * 更新用户信息(包括密码修好、用户锁定、用户解锁)
     *
     * @param user
     */
    @Override
    public void update(User user) {
        String userName = user.getUserName();
        User queryUser = userRepository.getUserByUserName(userName);
        if (queryUser == null) {
            throw new CRUDException(ExceptionCode.HAVE_NOT_DATA, "更新的用户不存在");
        }
        userRepository.save(user);
    }

    /**
     * 根据用户名获取用户信息
     *
     * @param userName
     * @return
     */
    @Override
    public User getUserByUserName(String userName) {
        User user = userRepository.getUserByUserName(userName);
        if (user == null) {
            throw new CRUDException(ExceptionCode.HAVE_NOT_DATA, "用户名不存在");
        }
        return user;
    }

    /**
     * 查询所有用户信息
     *
     * @return
     */
    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    /**
     * 用户登录
     *
     * @param user
     */
    @Override
    public User login(User user) {
        User u = userRepository.getUserByUserNameAndPassword(user.getUserName(),user.getPassword());
        if (u != null) {
            if (u.getLocked() == 1) {
                throw new CRUDException(ExceptionCode.USER_IS_LOCKED, "用户已被锁定！");
            }
            // 每登录一次增加5点积分
            u.setCredit(u.getCredit() + 5);
            // 更新访问时间
            u.setLastVisit(new Date());
            // 更新最后访问的IP地址
            u.setLastIp(UserContext.getRequest().getRemoteAddr());
            userRepository.updateCredit(u.getCredit(),new Date(),u.getUserName());
            // 返回增加积分后的登录信息
            User queryUser = userRepository.getUserByUserName(user.getUserName());

            //通知观察者,把日志写入数据库中
            setChanged();
            notifyObservers(queryUser);
        }
        return u;
    }

    /**
     * 用户更新密码
     *
     * @param user
     */
    @Override
    public void updatePassword(User user) {
        String userName = user.getUserName();
        String password = user.getPassword();
        User queryUser = userRepository.getUserByUserName(userName);
        if (queryUser == null) {
            throw new CRUDException(ExceptionCode.HAVE_NOT_DATA, "用户更新密码失败！");
        }
        if (!UserContext.getLoginUser().getUserName().equals(user.getUserName()) &&
                UserContext.getLoginUser().getUserType() != 2) {
            throw new CRUDException(ExceptionCode.HANDLE_NOT_ALLOWE, "操作不被允许！");
        }
        userRepository.updatePassword(userName, password);
    }

}
